#include "SpecParser.h"

#include "LocationParser.h"
#include "OutlineParser.h"
#include "SpecificationTypeParser.h"
#include "XformParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

SpecParser::SpecParser(
    QStringParser *&_nameParser
    , SpecificationTypeParser *&_specificationTypeParser
    , XformParser *&_xformParser
    , LocationParser *&_locationParser
    , OutlineParser *&_outlineParser
):    m_nameParser(_nameParser)
    , m_specificationTypeParser(_specificationTypeParser)
    , m_xformParser(_xformParser)
    , m_locationParser(_locationParser)
    , m_outlineParser(_outlineParser)
{

}

bool SpecParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Spec());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("name")))
    {
        data = reader->attributes().value(QStringLiteral("name"));
        if (!m_nameParser->parse(reader, data))
            return false;
        m_result->name = m_nameParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("name: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (m_specificationTypeParser->isSubstitution(name))
        {
            if (!m_specificationTypeParser->parse(reader))
                return false;
            auto result = m_specificationTypeParser->result();
            m_result->specificationTypeList.append(result);
        }
        else if (name == QStringLiteral("Xform"))
        {
            if (!m_xformParser->parse(reader))
                return false;
            auto result = m_xformParser->result();
            m_result->xformOptional = Optional<Xform*>(result);
        }
        else if (name == QStringLiteral("Location"))
        {
            if (!m_locationParser->parse(reader))
                return false;
            auto result = m_locationParser->result();
            m_result->locationOptional = Optional<Location*>(result);
        }
        else if (name == QStringLiteral("Outline"))
        {
            if (!m_outlineParser->parse(reader))
                return false;
            auto result = m_outlineParser->result();
            m_result->outlineOptional = Optional<Outline*>(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Spec *SpecParser::result()
{
    return m_result.take();
}

}